//
// Created by le on 13/12/2022.
//

#ifndef PLANEGAME_ENEMYPLANE_HPP
#define PLANEGAME_ENEMYPLANE_HPP

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <random>
#include <vector>

#ifdef __WIN32
#define Main SDL_main
#endif

#ifndef __WIN32
#define Main main
#endif

#define FRAMERATE 60 // 帧率
// 敌机类
class EnemyPlane
{
public:
    EnemyPlane(SDL_Renderer *renderer) : m_imageSurface(NULL), m_imageTexture(NULL)
    {
        m_log = fopen("../static/EnemyPlane.log", "w");
        if (!m_log)
        {
            exit(-1);
        }

        m_imageSurface = IMG_LoadPNG_RW(SDL_RWFromFile("../static/enemy_plane.png", "rb"));
        if (!m_imageSurface)
        {
            fprintf(m_log, "Cannot open enemy_plane.png! Error: %s\n", IMG_GetError());
            exit(-5);
        }

        // 获取图片的宽和高
        m_w = m_imageSurface->w;
        m_h = m_imageSurface->h;

        m_imageTexture = SDL_CreateTextureFromSurface(renderer, m_imageSurface);
        SDL_FreeSurface(m_imageSurface);
        m_imageSurface = NULL;

        if (!m_imageTexture)
        {
            fprintf(m_log, "Cannot create texture!\n");
            exit(-3);
        }
    }

    ~EnemyPlane()
    {
        if (m_log)
        {
            fclose(m_log);
        }

        if (m_imageTexture)
        {
            SDL_DestroyTexture(m_imageTexture);
        }
    }

    // 开始计时
    void start()
    {
        m_start = SDL_GetTicks();
    }

    // 渲染
    void render(SDL_Renderer *renderer, int weight)
    {
        uint32_t stop = SDL_GetTicks();
        static std::uniform_int_distribution<int> m_u(0, weight);

        // 每隔一段时间创建新飞机
        if (stop - m_start >= 550)
        {
            // 创建新飞机
            m_e.seed((unsigned)time(NULL) + m_e()); // 更新种子

            int w = m_u(m_e);
            SDL_Rect srcrect = {w, 0, m_w, m_h};

            fprintf(m_log, "更新位置：{%d,0,%d,%d}\n", w, m_w, m_h);

            m_position.push_back(srcrect);

            m_start = stop; // 重置计时器
        }

        // 飞机移动
        if (!m_position.empty())
        {
            int i = 0;
            for (i = 0; i < m_position.size(); ++i)
            {
                m_position[i].y += 1;                                           // 更新位置
                SDL_RenderCopy(renderer, m_imageTexture, NULL, &m_position[i]); // 渲染
            }
        }
    }

    std::vector<SDL_Rect> m_position; // 储存位置信息

private:
    SDL_Surface *m_imageSurface;
    SDL_Texture *m_imageTexture;
    FILE *m_log; // 日志

    uint32_t m_start;

    std::default_random_engine m_e; // 随机数引擎

public:
    int m_w; // 图片的宽
    int m_h; // 图片的高
};
#endif // PLANEGAME_ENEMYPLANE_H
